package com.czc.weather.push.weather.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.czc.weather.push.weather.entity.PushData;
import com.czc.weather.push.weather.service.PushDataService;
import com.czc.weather.push.weather.service.WxPushService;
import com.czc.weather.push.weather.service.WeathernfoService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


@RestController
@RequestMapping("/v1/api/cron")
public class CronPushWeatherController {

    @Autowired
    private WxPushService wxPushService;

    @Autowired
    private PushDataService pushDataService;
    
    @Autowired
    private WeathernfoService weathernfoService;

    @PostMapping("pushMorning")
    @Scheduled(cron = "0 30 7 * * ? ")
    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000)) 
    public void cronPushMorning() throws Exception {
        List<PushData> pushDatas = pushDataService.getPushData();
        for (PushData pushData : pushDatas) {
            try {
                List<String> uids = wxPushService.getWxPushUids(pushData);
                // 只有当获取到有效的UID时才进行推送
                if (!uids.isEmpty()) {
                    wxPushService.pushWeatherInfo(uids, pushData);
                }
            } catch (Exception e) {
                System.err.println("推送用户" + pushData.getMobile() + "的信息时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @PostMapping("pushEvening")
    @Scheduled(cron = "0 30 17 * * ? ")
    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000)) 
    public void cronPushEvening() throws Exception {
        List<PushData> pushDatas = pushDataService.getPushData();
        for (PushData pushData : pushDatas) {
            try {
                List<String> uids = wxPushService.getWxPushUids(pushData);
                // 只有当获取到有效的UID时才进行推送
                if (!uids.isEmpty()) {
                    wxPushService.pushWeatherInfo(uids, pushData);
                }
            } catch (Exception e) {
                System.err.println("推送用户" + pushData.getMobile() + "的信息时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    //增加推送应用apiKey 
    @PostMapping("savePushInfo")
    public ResponseEntity<String> savePushInfo(@RequestBody PushData pushData) throws Exception{
        return pushDataService.savePushInfo(pushData);
    }
}